package VBox;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

import Core.DB;

public class PortForward {
	Logger log = Logger.getAnonymousLogger();
	DB db = new DB();
	public int getPort(String vm,String jobID) {
		int port = maxPort() + 5;
		log.info(" port = "+port);
		reserve(port, vm, jobID);
			
			return port;
		
	}
	
	int maxPort()
	{
		String query = "SELECT max(port) from ports";
		int port=0;
		try {
		Statement st;
		st = db.getCon().createStatement();
		
		log.info("Executing : "+query);
		ResultSet res = st.executeQuery(query);
        
	       while (res.next()) {
	          port = res.getInt("max(port)");
	          //log.info("Available port : "+port);
		}	
		}
	    catch (SQLException e) {
			
			log.info(e.getMessage());
		}
	    return port;
}
	

	
	void reserve(int port, String vm, String jobID) {
		try {
			Statement st;
			st = db.getCon().createStatement();
			String query = "INSERT INTO ports(vmid,port,jobid) values ("+getVMID(vm)+" , "+port+", "+jobID+") " ; 
			log.info("Executing : "+query);
			@SuppressWarnings("unused")
			int res = st.executeUpdate(query);
        
       log.info("Successfully added entry in DB");
       //return 0;
	}
	catch (SQLException e) {
		log.severe("Error updating DB");
		log.severe(e.getMessage());
		
	//	return -1;
	}
	}
	
	int getVMID(String vm) {
	String query = "SELECT id from vms where vmname='"+vm+"'";
	int id=1000;
	try {
	Statement st;
	st = db.getCon().createStatement();
	
	log.info("Executing : "+query);
	ResultSet res = st.executeQuery(query);
    
       while (res.next()) {
          id = res.getInt("id");
          //log.info("Available port : "+port+5);
	}	
	}
    catch (SQLException e) {
		
		log.info(e.getMessage());
	}
    return id;
	}
	
	
	public void unreserve(String vm) {
		try {
			Statement st;
			st = db.getCon().createStatement();
			String query = "DELETE FROM ports where vmid =  "+ getVMID(vm); 
			log.info("Executing : "+query);
			@SuppressWarnings("unused")
			int res = st.executeUpdate(query);
        
       log.info("Successfully added entry in DB");
       //return 0;
	}
	catch (SQLException e) {
		log.severe("Error updating DB");
		log.severe(e.getMessage());
		
	//	return -1;
	}
	}
}
